package com.ca.ui.core.view.bar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.ca.ui.core.R;

public class MiniSearchBar extends ConstraintLayout {

    private int type;
    private Drawable lightIcon;
    private Drawable darkIcon;

    public View bg;
    public ImageView searchView;
    public TextView keywordView;

    public MiniSearchBar(@NonNull Context context) {
        super(context);
        initView(context, null);
    }

    public MiniSearchBar(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public MiniSearchBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {

        View view = LayoutInflater.from(context).inflate(R.layout.mini_search_bar_layout, this);

        bg = view.findViewById(R.id.bg);
        searchView = view.findViewById(R.id.iv_search);
        keywordView = view.findViewById(R.id.tv_keyword);

        if (attrs != null) {
            TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MiniSearchBar, 0, 0);

            lightIcon = array.getDrawable(R.styleable.MiniSearchBar_msb_lightIcon);
            darkIcon = array.getDrawable(R.styleable.MiniSearchBar_msb_darkIcon);
            type = array.getInteger(R.styleable.MiniSearchBar_msb_type, 0);

            array.recycle();
        }

        setType(type);
    }

    public Drawable getLightIcon() {
        return lightIcon;
    }

    public void setLightIcon(Drawable lightIcon) {
        this.lightIcon = lightIcon;
        setType(type);
    }

    public Drawable getDarkIcon() {
        return darkIcon;
    }

    public void setDarkIcon(Drawable darkIcon) {
        this.darkIcon = darkIcon;
        setType(type);
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
        if (type == 0) {
            searchView.setImageDrawable(lightIcon);
            keywordView.setTextColor(getResources().getColor(R.color.white_text));
            bg.setAlpha(0.3f);
        }
        else {
            this.type = 1;
            searchView.setImageDrawable(darkIcon);
            keywordView.setTextColor(getResources().getColor(R.color.secondary_text));
            bg.setAlpha(0.7f);
        }
    }

    public void light() {
        setType(0);
    }

    public void dark() {
        setType(1);
    }
}
